package org.opendream.roti.domain;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.opendream.roti.domain.NameEntityOld.EntityType;

/**
 * A node in a trie.
 * @author Brian Harris (brian_bcharris_net)
 */
public class TrieNode {
    char c;
    int occurances;
    TrieNode parent;
    public EntityType type;
    public Map<Character, TrieNode> children;
    
    public TrieNode(char c) {
        this.c = c;
        occurances = 0;
        children = null;
        parent = null;
    }
    
    public int insert(String s, int pos, EntityType type) {
        if (s == null || pos >= s.length())
            return 0; 

        // allocate on demand
        if (children == null)
            children = new HashMap<Character, TrieNode>();

        char c = s.charAt(pos);
        TrieNode n = children.get(c);

        // make sure we have a child with char c
        if (n == null) {
            n = new TrieNode(c);
            n.parent = this;
            children.put(c, n);
        }

        // if we are the last node in the sequence of chars
        // that make up the string
        if (pos == s.length()-1) {
            n.occurances++;
            n.type = type;
            return n.occurances;
        } else
            return n.insert(s, pos+1, type);
    }
    

    TrieNode lookup(String s, int pos) {
        if (s == null)
            return null;

        if (pos >= s.length() || children == null)
            return null;
        else if (pos == s.length()-1)
            return children.get(s.charAt(pos));
        else {
            TrieNode n = children.get(s.charAt(pos));
            return n == null ? null : n.lookup(s, pos+1);
        }
    }

    public String getWord() {
        ArrayList<Character> chs = new ArrayList<Character>();
        TrieNode tmp = this;
        int cnt = 0;
        while (tmp.parent != null)  {
            chs.add(tmp.c);
            tmp = tmp.parent;
            cnt++;
        }
        
        char[] cary = new char[cnt];
        int idx = 0;
        for (int i = cnt-1; i >= 0; i--) {
            cary[idx++] = chs.get(i);
        }
     
        return new String(cary);
    }
}